package com.adnaan.backend.utils;

import cn.hutool.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * author: adnaan
 * create: 2025-02-16 16:42
 * Description:
 */

public class WechatLoginUtil {
    // 替换为你的小程序 AppID
    private static final String APPID = "wx0bad6df89bb5fb21";
    // 替换为你的小程序 AppSecret
    private static final String APPSECRET = "adae7883c5f795e185cc3e1a9a8bba28";
    // 微信提供的 code2Session 接口地址
    private static final String CODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 使用 code 换取 openid 和 session_key
     *
     * @param code 小程序登录凭证
     * @return 微信返回的 JSON 字符串
     * @throws IOException 网络请求异常
     */
    public static JSONObject code2Session(String code) throws IOException {
        // 构建请求 URL
        String urlBuilder = CODE2SESSION_URL + "?appid=" + APPID +
                "&secret=" + APPSECRET +
                "&js_code=" + code +
                "&grant_type=authorization_code";

        // 创建 HttpClient 实例
        HttpClient httpClient = HttpClients.createDefault();
        // 创建 HttpGet 请求
        HttpGet httpGet = new HttpGet(urlBuilder);

        try {
            // 执行请求
            HttpResponse response = httpClient.execute(httpGet);
            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            // 解析 JSON 响应
            return new JSONObject(responseBody);
        } finally {
            // 释放资源
            httpGet.releaseConnection();
        }
    }

    public static void main(String[] args) {
        try {
            // 替换为实际的 code
            String code = "0a32D40w3TkLo43y540w3Mx4DF42D40z";
            JSONObject result = code2Session(code);
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
